package com.nsapi.niceschoolapi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nsapi.niceschoolapi.common.util.FileUtil;
import com.nsapi.niceschoolapi.entity.Rescource;
import com.nsapi.niceschoolapi.entity.Role;
import com.nsapi.niceschoolapi.entity.UserRole;
import com.nsapi.niceschoolapi.mapper.UserMapper;
import com.nsapi.niceschoolapi.entity.User;
import com.nsapi.niceschoolapi.mapper.UserRoleMapper;
import com.nsapi.niceschoolapi.service.UserService;
import com.nsapi.niceschoolapi.common.util.Encodes;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ResourceUtils;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@Service
@Transactional(rollbackFor = Exception.class)
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private UserRoleMapper userRoleMapper;

    @Override
    public User findUserByLoginName(String name) {
        Map<String,Object> map = new HashMap();
        map.put("loginName", name);
        return baseMapper.selectUserByMap(map);
    }

    @Override
    public User findUserById(String id) {
        Map<String,Object> map = new HashMap();
        map.put("id", id);
        return baseMapper.selectUserByMap(map);
    }

    @Override
    public int  userCount(String param) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("login_name",param).or().eq("email",param).or().eq("tel",param);
        int count = baseMapper.selectCount(wrapper);
        return count;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveUserRoles(String id, Set<Role> roleSet) {
        baseMapper.saveUserRoles(id,roleSet);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveUser(User user) {
        Encodes.entryptPassword(user);
        user.setLocked(false);
        baseMapper.insert(user);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateUser(User user) {
        dropUserRolesByUserId(user.getId());
        baseMapper.updateById(user);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteUser(User user) {
        user.setDelFlag(true);
        baseMapper.deleteById(user.getId());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void lockUser(User user) {
        user.setLocked(!user.getLocked());
        user.updateById();
    }

    @Override
    public String upload(MultipartFile file) throws IOException, NoSuchAlgorithmException {
        byte[] data = file.getBytes();  //将要上传的文件对象转换成字节数组(内存中数据)
        Rescource rescource = new Rescource();
        QueryWrapper<Rescource> wrapper = new QueryWrapper<>();
        String hash = FileUtil.calcETag(file.getInputStream(),file.getSize());
        wrapper.eq("hash",hash);
        wrapper.eq("source","local");
        rescource = rescource.selectOne(wrapper);
        if( rescource!= null){
            return rescource.getWebUrl();
        }
        String extName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        String fileName = UUID.randomUUID() + extName;
        String contentType = file.getContentType();
        StringBuffer sb = new StringBuffer(ResourceUtils.getURL("classpath:").getPath());
        String filePath = sb.append("static/upload/").toString();
        File targetFile = new File(filePath);
        if(!targetFile.exists()){
            targetFile.mkdirs();
        }
        FileOutputStream out = new FileOutputStream(filePath+fileName);
        out.write(data); //将保存到内存中的data字节数组输出到输出流中写入到指定路径中—— filePath+fileName
        out.flush();
        out.close();
        String webUrl = "/static/upload/"+fileName;
        rescource = new Rescource();
        rescource.setFileName(fileName);
        rescource.setFileSize(new java.text.DecimalFormat("#.##").format(file.getSize()/1024)+"kb");
        rescource.setHash(hash);
        rescource.setFileType(contentType);
        rescource.setWebUrl(webUrl);
        rescource.setSource("local");
        rescource.insert(); //实现向sys_resource表中新增一条记录。
        return webUrl;  //返回上传文件在项目中路径
    }


    @Override
    public int addUserRole(UserRole userRole) {
        return userRoleMapper.insert(userRole);
    }

    @Transactional(rollbackFor = Exception.class)
    public void dropUserRolesByUserId(String id) {
        baseMapper.dropUserRolesByUserId(id);
    }


}
